package com.lanluo.service.structure;

/**
 * 队列(链表实现)
 * @author
 * @date 2018-08-27-14:44
 */
public class Queue<Item> {
    private Node first; //指向最早的节点
    private Node last;  //指向最近的节点
    private int N;
    private class Node {
        Node next;
        Item item;
    }

    /**
     * 向表尾添加元素
     * @param item
     */
    public void enqueue(Item item) {
        Node oldLast = last;
        last = new Node();
        last.item = item;
        if(isEmpty()) {
            first = last;
        } else {
            oldLast.next = last;
        }
        N++;
    }

    /**
     * 从表头删除元素
     * @return
     */
    public Item dequeue() {
        Item item = first.item;
        first = first.next;
        if(isEmpty()) last = null;
        N--;
        return item;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public static void main(String[] args) {
        Queue<String> queue = new Queue<String>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i+"");
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.dequeue());
        }
    }

}